package service

import (
	"context"
	"go-mall/dao"
	"go-mall/pkg/e"
	"go-mall/pkg/util"
	"go-mall/serializer"
)

type OrderPay struct {
	OrderId string `json:"order_id" form:"order_id"`
}

func (service *OrderPay) PayDown(ctx context.Context, uId uint) serializer.Response {
	code := e.Success

	//查询这笔订单是否存在
	orderDao := dao.NewOrderDao(ctx)
	order, err := orderDao.GetOrderById(service.OrderId, uId)
	if err != nil {
		code = e.ErrorPayOrder
		return serializer.Response{
			Status: code,
			Msg:    e.GetMsg(code),
		}
	}

	//获取用户金额
	userDao := dao.NewUserDao(ctx)
	user, _ := userDao.GetUserById(uId)
	decryptMoney, _ := util.DecryptMoney(user.Money)      //用户余额解密
	decryptFloatMoney, _ := util.StrToFloat(decryptMoney) //str转float
	//用户余额不足
	if decryptFloatMoney-order.Money < 0 {
		code = e.ErrorMoneyNot
		return serializer.Response{
			Status: code,
			Msg:    e.GetMsg(code),
		}
	}

	//用户金额-订单金额，在重新加密赋值
	overMoney := decryptFloatMoney - order.Money           //金额相减
	userMoney := util.FloatToStr(overMoney)                //转str
	remainingMoney, _ := util.EncryptMoney(userMoney)      //在加密
	err = userDao.UpdateUserMoneyById(uId, remainingMoney) //更新
	//更新用户余额失败
	if err != nil {
		code = e.ErrorUpdateUserMoney
		return serializer.Response{
			Status: code,
			Msg:    e.GetMsg(code),
		}
	}
	//获取所有订单下所有的item给商家加收益
	orderItems, _ := orderDao.GetOrderItemById(service.OrderId)
	productDao := dao.NewProductDao(ctx)
	for _, item := range orderItems {
		boss, _ := userDao.GetUserById(item.BossId)
		product, _ := productDao.GetProductById(item.ProductId)
		//	解密商家金额
		bossMoney, _ := util.DecryptMoney(boss.Money)
		boosMoneyFloat, _ := util.StrToFloat(bossMoney)                //商家金额str转float64
		productMoneyFloat, _ := util.StrToFloat(product.DiscountPrice) //商家金额str转float64
		numMoney := boosMoneyFloat + productMoneyFloat                 //商家原本金额+商品金额
		numStrMoney := util.FloatToStr(numMoney)                       //float转str
		encryptMoney, _ := util.EncryptMoney(numStrMoney)              //将商家金额在加密
		err = userDao.UpdateUserMoneyById(boss.ID, encryptMoney)       //更新数据库商家金额
		if err != nil {
			code = e.Error
			return serializer.Response{
				Status: code,
				Msg:    e.GetMsg(code),
			}
		}
	}

	//支付完成，商家收益添加完成，将订单的支付状态改成2
	err = orderDao.UpdatePayType(service.OrderId)
	if err != nil {
		code = e.Error
		return serializer.Response{
			Status: code,
			Msg:    err.Error(),
		}
	}

	return serializer.Response{
		Status: code,
		Msg:    e.GetMsg(code),
	}
}
